import React, {useEffect, useState} from 'react';
import axios from "axios";
import {Button, Table, Tag, Modal} from "antd";
import {DeleteOutlined, EditOutlined,ExclamationCircleOutlined,UploadOutlined} from "@ant-design/icons";
import {Link, useNavigate} from "react-router-dom";


const {confirm} = Modal

const NewsDraft = () => {

    const [dataSource,setDataSource]=useState([])
    const {username} = JSON.parse(localStorage.getItem('token'))
    const navigate=useNavigate()

    useEffect(()=>{
        axios.get(`/news?author=${username}&auditState=0&_expand=category`).then(res=>{
            const list = res.data
            setDataSource(list)
        })
    },[username])
    const columns = [
        {
            title:'ID',
            dataIndex:'id',
            render:(id)=>{
                return <b>{id}</b>
            }
        },
        {
            title: '新闻标题',
            dataIndex: 'title',
            render:(title,item)=>{
                return <Link to={`/news-manage/preview/${item.id}`}>{title}</Link>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            render:(key)=>{
                return <Tag color={"blue"}>{key}</Tag>
            }
        },
        {
            title: '分类',
            dataIndex: 'category',
            render:(category)=>{
                return category.title
            }
        },
        {
            title: '操作',
            render:(item)=>{
                return <div>
                    <Button shape='circle' type={"primary"} icon={<EditOutlined/>}  style={{marginRight:'5px'}} onClick={()=>{
                        navigate(`/news-manage/update/${item.id}`)
                    }}/>
                    <Button shape="circle" danger icon={<DeleteOutlined/>}
                            onClick={()=>{confirmDel(item)}} style={{marginRight:'5px'}}/>
                    <Button shape='circle' type={"primary"} icon={<UploadOutlined/>} onClick={()=>{handleCheck(item.id)}}/>
                </div>
            }
        }
    ]
    function confirmDel(item) {
        confirm({
            title: '确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                deleteMethod(item);
            },
            onCancel() {
                console.log('取消');
            },
        });
    }

    const deleteMethod = (item) =>{
        setDataSource(dataSource.filter(data=>data.id!==item.id))
        axios.delete(`/news/${item.id}`)
    }

    const handleCheck=(id)=>{
        axios.patch(`/news/${id}`,{
            auditState:1
        }).then(res=>{
            navigate('/audit-manage/list')
        })
    }

    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{pageSize:10}} rowKey={item=>item.id}/>
        </div>
    );
};

export default NewsDraft;